import os
import zipfile

import pymysql

from config import MySQLConfig


class DBUtils(object):
    def __init__(self, host=None, username=None, password=None, db=None):

        if host == None or username == None or password == None or db == None:
            host = MySQLConfig.host
            username = MySQLConfig.username
            password = MySQLConfig.password
            db = MySQLConfig.db

        self.conn = pymysql.connect(
            host=host,
            user=username,
            password=password,
            db=db,
        )
        self.cur = self.conn.cursor()

    def insert(self, sql=None):
        if sql is None:
            return 0

        self.cur.execute(sql)
        self.conn.commit()
        return 1

    def query(self,sql=None):

        host = MySQLConfig.host
        username = MySQLConfig.username
        password = MySQLConfig.password
        db = MySQLConfig.db

        self.conn = pymysql.connect(
            host=host,
            user=username,
            password=password,
            db=db,
        )
        self.cur = self.conn.cursor()
        if sql is None:
            return 0
        self.cur.execute(sql)
        result = self.cur.fetchall()
        return result

    def delete(self,sql=None):
        if sql is None:
            return 0
        self.cur.execute(sql)
        self.conn.commit()


    def __del__(self):
        self.cur.close()
        self.conn.close()

class Utils:
    @staticmethod
    def del_dir(path,status=0):

        ls = os.listdir(path)
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                Utils.del_dir(c_path,1)
                os.rmdir(c_path)
            else:
                os.remove(c_path)
        if status == 0:
            os.rmdir(path)

    @staticmethod
    def zip_dir(path):
        dataset_dir = path.split('\\')[-2]
        temp = os.path.join(path,"..")
        file_name = dataset_dir+'.zip'
        file_path = os.path.join(temp,file_name)
        z = zipfile.ZipFile(file_path, 'w', zipfile.ZIP_DEFLATED)
        for dirpath, dirnames, filenames in os.walk(path):
            fpath = dirpath.replace(path, '')  # 这一句很重要，不replace的话，就从根目录开始复制
            fpath = fpath and fpath + os.sep or ''  # 这句话理解我也点郁闷，实现当前文件夹以及包含的所有文件的压缩
            for filename in filenames:
                z.write(os.path.join(dirpath, filename), fpath + filename)
        z.close()
        return file_path

dbutil = DBUtils()

if __name__ == '__main__':
    path = r'E:\毕业设计\code\Microservices\files\dataset\demo'
    path = os.path.join(path,"")
    Utils.zip_dir(path)